package com.example.wang.bindview.api;

import android.app.Activity;
import android.view.View;

import com.example.wang.bindview.api.finder.ActivityFinder;
import com.example.wang.bindview.api.finder.Finder;
import com.example.wang.bindview.api.finder.ViewFinder;

import java.util.HashMap;
import java.util.Map;

public class ViewBinder {
    public ViewBinder(){
        throw new AssertionError("no .instance");
    }
    private static final ActivityFinder ACTIVITY_FINDER = new ActivityFinder();
    private static final ViewFinder VIEW_FINDER = new ViewFinder();
    private static Map<String, Injector> FINDER_MAP = new HashMap<>();
    public static void bind(Activity activity){
        bind(activity, activity, ACTIVITY_FINDER);
    }
    public static void bind(View view){
        bind(view, view);
    }
    public static void bind(Object target, View view){
        bind(target, view, VIEW_FINDER);
    }

    /**
     * 执行注入。
     * @param target
     * @param source
     * @param finder
     */
    public static void bind(Object target, Object source, Finder finder){
        String className=target.getClass().getName();
        try {
            Injector injector = FINDER_MAP.get(className);
            if(injector == null){
                Class<?> finderClass = Class.forName(className + "$$Injector");
                injector = (Injector)finderClass.newInstance();
                FINDER_MAP.put(className, injector);
            }
            injector.inject(target, source, finder);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
